package com.xingmei.custom.queue;

import com.xingmei.User;

import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {

    static boolean shouldBreak = false;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        ArrayQueue<User> queue = new ArrayQueue<User>(10);
        executorService.submit(new QueueDataProducer(queue));
        executorService.submit(new QueueDataConsumer(queue));
        Thread.sleep(1000*20);
        shouldBreak = true;
        System.out.println(queue.sumDataCount);
    }

    static class QueueDataProducer implements Runnable {

        ArrayQueue<User> queue;

        public QueueDataProducer(ArrayQueue<User> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            while (!shouldBreak) {
                User user = new User();
                user.setName(UUID.randomUUID().toString());
                user.setAge(18);
                try {
                    queue.put(user);
                    System.out.println("生产者,name: " + user.getName());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    static class QueueDataConsumer implements Runnable {
        ArrayQueue<User> queue;
        public QueueDataConsumer(ArrayQueue<User> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            while (!shouldBreak) {
                try {
                    User user = (User) queue.take();
                    System.out.println("消费者,name: " + user.getName());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
